package org.dreamwork.jasmine2.engine;

import org.dreamwork.util.NameValueCollection;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-2-4
 * Time: 10:05:59
 */
public class HttpRequestAdapter {
    private HttpServletRequest request;


    public HttpRequestAdapter (HttpServletRequest request) {
        this.request = request;
    }

    public NameValueCollection fill () {
        NameValueCollection coll = new NameValueCollection ();
        for (Enumeration en = request.getParameterNames (); en.hasMoreElements (); ) {
            String key = (String) en.nextElement ();
            if ("__event.sender".equalsIgnoreCase (key) ||
                "__event.type".equalsIgnoreCase (key)   ||
                "__event.attr".equalsIgnoreCase (key)   ||
                "__viewstate".equalsIgnoreCase (key)
            ) continue;
            String[] values = request.getParameterValues (key);
            if (values == null || values.length == 0) continue;
            if (values.length == 1) {
                coll.add (key, values [0]);
            } else {
                StringBuffer builder = new StringBuffer ();
                for (int i = 0; i < values.length; i ++) {
                    if (i > 0) builder.append (',');
                    builder.append (values [i]);
                }
                coll.add (key, builder.toString ());
            }
        }

        return coll;
    }
}